<template>
  <div class="createTemplate">
    <!-- 顶部按钮 -->
    <div class="topBtn">
      <div class="save">
        <el-button type="primary" size="small" round @click="saveData">保存</el-button>
      </div>
    </div>
    <!-- 操作区域 -->
    <div class="template">
      <!-- 左边 -->
      <div class="left">
        <el-tabs v-model="modelName" :before-leave="beforeChange">
          <el-tab-pane label="组件列表" name="first">
            <WidgetsList :widgetList="widgetList" @onWidgetMouseDown="onWidgetMouseDown">
            </WidgetsList>
          </el-tab-pane>
        </el-tabs>
      </div>
      <!-- 中间 -->
      <div class="center">
        <!-- 模板信息 -->
        <div class="navInfo pointer" @click="showModelInfo">
          <div class="title">{{ modelinfo.modelName }}</div>
          <div class="tips">模板操作提示 <i class="el-icon-warning"></i>
            <!-- 模板创建提示 -->
            <div class="tipsCon">
              <div>1.模板内海报位排序从"1"开始。</div>
              <div>2.模板示例图片可传可不传。</div>
              <div>3.此模板展示与EPG呈现无关。</div>
            </div>
          </div>
        </div>
        <!-- 操作间 -->
        <div class="panle"
          :style="bgImg !== '' ? { background: 'url(' + bgImg + ')', backgroundSize: 'cover', backgroundPosition: 'center center' } : ''">
          <div class="view" @click.stop @click.prevent @drop="onDrop" @dragover="dragOver">
            <VueDragResizezble class="item" ref="widget" v-for="(item, index) in modelList" :key="index"
              :w="item.style.w == '' || item.style.w < 10 ? 10 : parseInt(item.style.w / 4 * 3)"
              :h="item.style.h == '' || item.style.h < 10 ? 10 : parseInt(item.style.h / 4 * 3)" :x="item.style.x" :y="item.style.y"
              :active="false" :maxWidth="1133" @dragging="onDragging" @resizing="onResize" :parent="true" :debug="false"
              :snap="true" :snapTolerance="5" @refLineParams="getRefLineParams" @activated="selectType(item)">
              <WidgetsListAll :com="item.com" :widgetData="item" :type="type"></WidgetsListAll>
              <i @mousedown.stop.prevent="deleteItem($event, index)" class="el-icon-error"></i>
            </VueDragResizezble>
            <!--辅助线-->
            <span class="ref-line v-line" v-for="(item, idx1) in vLine" :key="idx1 + 'a'" v-show="item.display"
              :style="{ left: item.position, top: item.origin, height: item.lineLength }"></span>
            <span class="ref-line h-line" v-for="(item, idx2) in hLine" :key="idx2 + 'b'" v-show="item.display"
              :style="{ top: item.position, left: item.origin, width: item.lineLength }"></span>
            <!--辅助线END-->
          </div>
        </div>
      </div>
      <!-- 右边 -->
      <div class="right">
        <el-tabs v-model="activeName">
          <el-tab-pane label="模板配置" name="first">
            <DetailInfo :modelData="modelinfo" @toImage="initScreenShort"></DetailInfo>
          </el-tab-pane>
          <el-tab-pane v-if="isRight" label="组件设置" name="second">
            <WidgetAttrList :comData="propsData"></WidgetAttrList>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script>
// 拖拽插件
import VueDragResizezble from '@/commont/plugins/draggable/vue-draggable-resizable';
import '@/commont/plugins/draggable/vue-draggable-resizable.css';
// 自定义截屏
import ScreenShot from "js-web-screen-shot";

// 组件
import DetailInfo from '@/components/singlePage/modelCommon/detailInfo.vue';//模板信息
import WidgetsList from '@/components/singlePage/model/widgetsList.vue';//组件集合
import WidgetsListAll from '@/components/singlePage/model/widgetsListAll.vue';//组件列表
import WidgetAttrList from '@/components/singlePage/model/widgetAttrList.vue';//组件属性列表

import { DETAIL_LIST_WIDGET, CUSTOM_WIDGET_LIST } from '@/commont/constants/config';//静态配置
let widgetX = 0;//当前组件的x位置
let widgetY = 0;//当前组件的y位置
let currentWidget = null;//当前组件
let index = 1;//轮播图的位置排序

export default {
  components: {
    VueDragResizezble,
    DetailInfo,
    WidgetsList, WidgetsListAll, WidgetAttrList,
  },
  props: {},
  data() {
    return {
      /****** 左边组件列表 ******/
      widgetList: DETAIL_LIST_WIDGET,
      customWidgetList: CUSTOM_WIDGET_LIST,
      modelName: "first",
      /****** 中间模板信息 ******/
      bgImg: require('../../assets/modelBg.png'),//背景图
      type: 'widget',
      modelList: [],
      vLine: [],
      hLine: [],
      /****** 右边属性值 ******/
      modelinfo: {
        modelName: '',
        modelType: '',
        modelBuss: '',
        modelPosi: 2,
        modelSign: '',
        modelSignAdd: '',
        viewImg: '',
        modelDetails: ''
      },
      activeName: "first",
      isRight: false,
      propsData: {},//属性值
    }
  },
  methods: {
    /*********** 顶部 *************/
    // 保存
    saveData() {
      console.log(this.modelList);
      let arr = [
        { floorNum: 1, name: '楼层一' },
        { floorNum: 1, name: '楼层一' },
        { floorNum: 2, name: '楼层二' },
        { floorNum: 1, name: '楼层一' },
        { floorNum: 3, name: '楼层三' },
      ]


      let detailData = this.sortClass(arr)
      console.log(detailData);


    },
    // 分组
    sortClass(sortData) {
      const groupBy = (array, f) => {
        let groups = {};
        array.forEach((o) => {
          let group = JSON.stringify(f(o));
          groups[group] = groups[group] || [];
          groups[group].push(o);
        });
        return Object.keys(groups).map((group) => {
          return groups[group];
        });
      };
      const sorted = groupBy(sortData, (item) => {
        return item.floorNum; // 返回需要分组的对象
      });
      return sorted;
    },
    // 查找数组中重复的值
    findSame(arr) {
      arr.sort();
      for (var i = 0; i < arr.length - 1; i++) {
        if (arr[i] == arr[i + 1]) {
          console.log("找到相同元素，值为：" + arr[i]);
          return true;
        }
      };
      return false;
    },

    /*********** 左侧 *************/
    // 左边组件切换
    beforeChange(name) {
      if (name == 'first') {
        this.isRight = false;
        this.activeName = "first";
      } else if (name == 'second') {
        this.isCustomData = false;
        this.activeName = "first";
      }
    },
    // 鼠标按下组件事件
    onWidgetMouseDown(e, widget) {
      widgetX = e.offsetX;
      widgetY = e.offsetY;
      currentWidget = widget;
    },

    /*********** 中间 *************/
    // 展示模板信息
    showModelInfo() {
      this.activeName = "first";
      this.isRight = false;
      this.propsData = {};
      this.customData = {};
    },
    // 展示右边组件操作数据
    selectType(item) {
      this.isRight = false;
      this.propsData = item;
      this.activeName = 'second';
      console.log('小组件属性值', this.propsData);
      this.$nextTick(() => this.isRight = true);
    },
    // 删除组件
    deleteItem(e, index) {
      e.preventDefault();
      e.stopPropagation();
      this.modelList.splice(index, 1);
      this.activeName = "first";
      this.isRight = false;
      this.propsData = {};
    },
    // 阻止默认事件
    dragOver(e) {
      e.preventDefault();//阻止默认事件
      e.stopPropagation();//阻止事件冒泡
    },
    // 组件缩放调整大小
    onResize(x, y, w, h) {
      this.propsData.style.w = parseInt(w / 3 * 4);
      this.propsData.style.h = parseInt(h / 3 * 4);
      this.propsData.style.x = x;
      this.propsData.style.y = y;
    },
    // 组件拖动时的位置
    onDragging(x, y) {
      this.propsData.style.x = x;
      this.propsData.style.y = y;
    },
    // 辅助线回调事件
    getRefLineParams(params) {
      const { vLine, hLine } = params;
      this.vLine = vLine;
      this.hLine = hLine;
    },
    // 拖放结束
    onDrop(e) {
      currentWidget.default.value = [];
      // 小组件
      if (this.modelName != 'second') {
        // 特殊
        if (currentWidget.type == 'textposter') { //文字海报
          currentWidget.default.value = [
            { index: 1, title: '文字海报', name: '', url: require('@/assets/img/r-1.jpg') },
          ]
          this.modelList.push({
            type: currentWidget.type,
            label: currentWidget.label,
            com: currentWidget.component,
            floorName: currentWidget.floorName,
            floorNum: currentWidget.floorNum,
            style: {
              x: e.offsetX - widgetX,
              y: e.offsetY - widgetY,
              w: currentWidget.default.w,
              h: currentWidget.default.h,
            },
            value: currentWidget.default.value,
          })
        }
        else if (currentWidget.type == 'detailBox') { //影片详情
          currentWidget.default.value = [
            {
              logo: require('@/assets/images/img-1.png'),
              video: require('@/assets/img/1.jpg'),
              title: '舍我其谁',
              score: '8.1',
              corporate: '天翼视讯传媒有限公司提供',
              year: '2021',
              are: '中国大陆',
              total: '41',
              director: '鞠觉亮',
              actor: '李兰迪，牛骏峰，韩玖诺',
              introduction: '（内容来源于华数）天才青年围棋手胜景初，黑马姿态一战成名，轰动围棋界。从不接受任何采访的他成为了众多媒体争相报道的对象。实习记者程了帮盛景初解围，却被误会为他的女朋友，两人假戏真做等候收到i的就哦啊收到都好都好是等哈收到都好都好的话大撒大撒大大飒飒大苏打大苏打大大是发售公告发布',
            },
          ]
          this.modelList.push({
            type: currentWidget.type,
            label: currentWidget.label,
            com: currentWidget.component,
            floorName: currentWidget.floorName,
            floorNum: currentWidget.floorNum,
            style: {
              x: e.offsetX - widgetX,
              y: e.offsetY - widgetY,
              w: currentWidget.default.w,
              h: currentWidget.default.h,
            },
            value: currentWidget.default.value,
            isShow: currentWidget.default.isShow,
            recommendList: [],
          })
        }
        //其他
        else {
          currentWidget.default.value = [
            { index: 1, name: '', url: require('@/assets/img/r-1.jpg') },
          ]
          this.modelList.push({
            type: currentWidget.type,
            label: currentWidget.label,
            com: currentWidget.component,
            floorName: currentWidget.floorName,
            floorNum: currentWidget.floorNum,
            style: {
              x: e.offsetX - widgetX,
              y: e.offsetY - widgetY,
              // ...currentWidget.default,  //es6 解构
              w: currentWidget.default.w,
              h: currentWidget.default.h,
            },
            value: currentWidget.default.value,
          })
        }
      }
      console.log("模板组件：", this.modelList);
    },

    /*********** 右侧 *************/
    // 模板自定义截屏
    initScreenShort() {
      if (this.modelinfo.viewImg != "") {
        this.$message({ message: '已上传模板截图，若要重新上传请先删除！', type: 'error' });
      } else {
        const screenShotHandler = new ScreenShot({
          enableWebRtc: false, // 是否启用webrtc，值为boolean类型，值为false则使用html2canvas来截图
          completeCallback: this.callback, //确认的回调函数
          closeCallback: this.closeFn, // 截图关闭回调函数
          level: 11, //截图的层级
          loadCrossImg: true, //允许图片跨域
        });
      }
    },
    //截图确认按钮回调函数
    callback(base64data) {
      // 截图路径 base64
      // console.log('图片路径：',base64data);
      requestModel({ img: base64data }, 'screenshot').then(res => {
        let { result_code, result_msg, data } = res;
        if (result_code == 0) {
          this.modelinfo.viewImg = data;
          this.$message({ message: '截图成功', type: 'success' });
        } else {
          this.$Message.error(result_msg || this.$cfg.COMMONERRORMSG);
        }
      })
    },
    closeFn(e) {
      console.log(e);
    },


  },
  filters: {},
}
</script>

<style lang="scss" scoped>
.createTemplate {
  width: 100%;
  height: 100%;

  // 顶部按钮
  .topBtn {
    padding: 15px;
    background-color: #FFFFFF;
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }

  // 操作区域
  .template {
    width: 100%;
    height: calc(100vh - 155px);
    margin-top: 15px;
    padding: 15px;
    background-color: #FFFFFF;
    display: flex;

    // 左边小组件
    .left {
      width: 260px;
      height: 100%;
      overflow-y: auto;
      box-shadow: 0px 2px 8px 0px #ccc;
    }

    // 中间面板
    .center {
      width: calc(100% - 700px);
      height: 100%;
      margin: 0 20px;
      box-shadow: 0px 2px 8px 0px #ccc;
      position: relative;

      .navInfo {
        width: 100%;
        height: 42px;
        position: absolute;
        top: 0;
        left: 0;
        background: #fff;
        transition: all .3s;
        padding: 10px 20px;
        border-bottom: 1px solid #cdcdcd;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .title {
          font-size: 16px;
        }

        .tips {
          color: #e6a23c;

          &:hover {
            .tipsCon {
              display: block;
            }
          }
        }

        // 模板操作提示
        .tipsCon {
          display: none;
          background: #fff;
          width: 255px;
          padding: 10px;
          border: 1px solid #cdcdcd;
          position: absolute;
          right: 0;
          top: 40px;
          z-index: 9;
        }
      }

      .panle {
        margin-top: 42px;
        height: calc(100% - 42px);
        background: linear-gradient(-90deg, rgba(82, 82, 82, 0.1) 1px, transparent 1px) 0% 0% / 20px 20px, linear-gradient(rgba(82, 82, 82, 0.1) 1px, transparent 1px) 0% 0% / 20px 20px;
        padding: 10px 15px;
        display: flex;
        justify-content: center;

        .view {
          width: 860px;
          height: 100%;
          border: 1px solid blue;
          overflow-y: auto;
          overflow-x: hidden;
          position: relative;

          .item {
            &:hover {
              cursor: pointer;
              transform: scale(0.99);
              border-radius: 2px;
              box-shadow: 0 0 3px #afafaf;

              .el-icon-error {
                display: block;
              }
            }

            .el-icon-error {
              position: absolute;
              right: -10px;
              top: -6px;
              color: red;
              font-size: 25px;
              cursor: pointer;
              display: none;
              z-index: 9999;
            }
          }
        }
      }
    }

    // 右边属性
    .right {
      width: 410px;
      height: 100%;
      overflow-y: auto;
      box-shadow: 0px 2px 8px 0px #ccc;
    }
  }
}
</style>